document.getElementById('customGradeToggle').addEventListener('change', function () {
    document.getElementById('gradeLevelsContainer').style.display = this.checked ? 'block' : 'none';

    // 当取消选中时，清空所有分值等级输入
    if (!this.checked) {
        document.querySelectorAll('#gradeLevels input').forEach(input => input.value = '');
    }
});

document.getElementById('addGradeLevel').addEventListener('click', function () {
    const template = document.querySelector('.grade-level').cloneNode(true);
    template.querySelectorAll('input').forEach(input => input.value = '');
    document.getElementById('gradeLevels').appendChild(template);
});

document.getElementById('uploadForm').addEventListener('submit', function (e) {
    e.preventDefault();

    // 显示加载状态
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';

    const formData = new FormData(this);

    if (document.getElementById('customGradeToggle').checked) {
        const gradeLevels = [];
        const gradeNames = document.getElementsByName('grade_names[]');
        const gradeMins = document.getElementsByName('grade_min[]');
        const gradeMaxs = document.getElementsByName('grade_max[]');

        // 只收集完整填写的等级设置
        for (let i = 0; i < gradeNames.length; i++) {
            // 检查是否所有字段都已填写
            if (gradeNames[i].value && gradeMins[i].value && gradeMaxs[i].value) {
                gradeLevels.push({
                    name: gradeNames[i].value,
                    min: parseFloat(gradeMins[i].value),
                    max: parseFloat(gradeMaxs[i].value)
                });
            }
        }

        // 只有当有完整的等级设置时才添加到表单数据
        if (gradeLevels.length > 0) {
            formData.append('grade_levels', JSON.stringify(gradeLevels));
        }
    }

    fetch('/upload', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (response.ok) {
                window.location.href = '/';
                return;
            }
            // 尝试解析错误信息
            return response.json().then(data => {
                throw new Error(data.error || '上传失败');
            });
        })
        .catch(error => {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;

            // 显示错误信息
            alert('错误：' + error.message);
        });
});